package cc.fine.svc.main.service.impl.rel;

import cc.fine.svc.config.redis.utils.RedisCache;
import cc.fine.svc.main.bean.po.RelUserVideoHistory;
import cc.fine.svc.main.bean.po.TblUserCount;
import cc.fine.svc.main.mapper.RelUserVideoHistoryMapper;
import cc.fine.svc.main.service.RelUserVideoHistoryService;
import cc.fine.svc.main.service.VideoCountService;
import cc.fine.svc.main.service.tbl.TblUserCountService;
import cc.fine.svc.main.service.tbl.TblVideoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wyihe
 * @since 2023-10-28
 */
@Service
@Transactional
public class RelUserVideoHistoryServiceImpl extends ServiceImpl<RelUserVideoHistoryMapper, RelUserVideoHistory> implements RelUserVideoHistoryService {

    @Autowired
    private VideoCountService videoCountService;

    @Autowired
    private TblUserCountService userCountService;

    @Autowired
    private TblVideoService videoService;

    @Autowired
    private RedisCache redisCache;

    @Override
    public void view(RelUserVideoHistory history) {
        history.setTime(new Date());

        QueryWrapper<RelUserVideoHistory> w=  new QueryWrapper<>();
        w.eq("user_id", history.getUserId());
        w.eq("video_id", history.getVideoId());

        saveOrUpdate(history, w);
        videoCountService.increaseView(history.getVideoId());

        // 更新 userCount 表
        TblUserCount userCount = userCountService.getById(history.getUserId());
        if (userCount == null) userCount = new TblUserCount();
        userCount.setHistories(userCount.getHistories() + 1);
        userCountService.saveOrUpdate(userCount);


        // 添加进redis的历史记录
        List<String> cache = redisCache.getCacheMapValue(RelUserVideoHistoryService.History_Record_map, history.getUserId());
        if (cache == null) {
            cache = new ArrayList<>();
        }
        cache.add(history.getVideoId());
        redisCache.setCacheMapValue(RelUserVideoHistoryService.History_Record_map, history.getUserId(), cache);

    }

    @Override
    public List<Map<String, Object>> historyVideo(String userId, Date startTime, Date endTime) {
        List<String> videoIds = getHistoryVideoIds(userId, startTime, endTime);
        return videoService.searchByVideoIds(videoIds, 0, videoIds.size());
    }

    @Override
    public List<String> getHistoryVideoIds(String userId, Date startTime, Date endTime) {
        return baseMapper.selectHistoryVideoIds(userId, startTime, endTime);
    }
}
